package com.photo.photePro.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.photo.photePro.common.R;
import com.photo.photePro.entity.Photo;
import com.photo.photePro.entity.Vote;
import com.photo.photePro.service.PhotoService;
import com.photo.photePro.service.VoteService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 投票功能Controller
 */
@Slf4j
@RestController
@RequestMapping("/votes")
public class VoteController {

    @Autowired
    private VoteService voteService;
    
    @Autowired
    private PhotoService photoService;

    /**
     * 用户给作品投票
     */
    @PostMapping
    public R<String> vote(@RequestBody Vote vote) {
        // 查询是否已经投过票
        LambdaQueryWrapper<Vote> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Vote::getPhotoId, vote.getPhotoId());
        queryWrapper.eq(Vote::getUserId, vote.getUserId());
        Vote existVote = voteService.getOne(queryWrapper);
        
        if (existVote != null) {
            return R.error("您已经给该作品投过票了");
        }
        
        // 保存投票
        vote.setCreateTime(LocalDateTime.now());
        vote.setUpdateTime(LocalDateTime.now());
        voteService.save(vote);
        
        // 更新作品评分和投票数
        Photo photo = photoService.getById(vote.getPhotoId());
        if (photo != null) {
            // 重新计算平均分
            LambdaQueryWrapper<Vote> voteQuery = new LambdaQueryWrapper<>();
            voteQuery.eq(Vote::getPhotoId, vote.getPhotoId());
            List<Vote> votes = voteService.list(voteQuery);
            
            double totalScore = 0;
            for (Vote v : votes) {
                totalScore += v.getScore();
            }
            
            double avgScore = totalScore / votes.size();
            photo.setScore(avgScore);
            photo.setVoteCount(votes.size());
            photo.setUpdateTime(LocalDateTime.now());
            
            photoService.updateById(photo);
        }
        
        return R.success("投票成功");
    }

    /**
     * 查询作品的投票列表
     */
    @GetMapping("/photo/{photoId}")
    public R<List<Vote>> listByPhotoId(@PathVariable Long photoId) {
        LambdaQueryWrapper<Vote> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Vote::getPhotoId, photoId);
        queryWrapper.orderByDesc(Vote::getCreateTime);
        
        List<Vote> list = voteService.list(queryWrapper);
        return R.success(list);
    }

    /**
     * 分页查询用户的投票历史
     */
    @GetMapping("/user")
    public R<Page<Vote>> pageUserVotes(int page, int pageSize, Long userId) {
        log.info("分页查询用户投票: page={}, pageSize={}, userId={}", page, pageSize, userId);
        
        if (userId == null) {
            return R.error("用户ID不能为空");
        }
        
        Page<Vote> pageInfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<Vote> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Vote::getUserId, userId);
        queryWrapper.orderByDesc(Vote::getCreateTime);
        
        voteService.page(pageInfo, queryWrapper);
        return R.success(pageInfo);
    }

    /**
     * 查询用户的投票历史（不分页）
     */
    @GetMapping("/user/{userId}")
    public R<List<Vote>> listByUserId(@PathVariable Long userId) {
        LambdaQueryWrapper<Vote> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Vote::getUserId, userId);
        queryWrapper.orderByDesc(Vote::getCreateTime);
        
        List<Vote> list = voteService.list(queryWrapper);
        return R.success(list);
    }
    
    /**
     * 取消投票
     */
    @DeleteMapping("/{id}")
    public R<String> cancelVote(@PathVariable Long id) {
        log.info("取消投票: id={}", id);
        
        Vote vote = voteService.getById(id);
        if (vote == null) {
            return R.error("投票记录不存在");
        }
        
        // 检查投票时间是否在24小时内
        LocalDateTime voteTime = vote.getCreateTime();
        LocalDateTime now = LocalDateTime.now();
        if (voteTime.plusHours(24).isBefore(now)) {
            return R.error("只能取消24小时内的投票");
        }
        
        // 移除投票
        boolean result = voteService.removeById(id);
        if (!result) {
            return R.error("取消失败");
        }
        
        // 更新作品评分和投票数
        Photo photo = photoService.getById(vote.getPhotoId());
        if (photo != null) {
            // 重新计算平均分
            LambdaQueryWrapper<Vote> voteQuery = new LambdaQueryWrapper<>();
            voteQuery.eq(Vote::getPhotoId, vote.getPhotoId());
            List<Vote> votes = voteService.list(voteQuery);
            
            if (votes.isEmpty()) {
                photo.setScore(0.0);
                photo.setVoteCount(0);
            } else {
                double totalScore = 0;
                for (Vote v : votes) {
                    totalScore += v.getScore();
                }
                
                double avgScore = totalScore / votes.size();
                photo.setScore(avgScore);
                photo.setVoteCount(votes.size());
            }
            
            photo.setUpdateTime(LocalDateTime.now());
            photoService.updateById(photo);
        }
        
        return R.success("取消投票成功");
    }
} 